<template>
  <h2>App组件</h2>
  <p>{{ num }}</p>
  <button @click="update">定义函数更新数据</button>
  <button @click="num++">直接修改数据</button>
  <p>{{ person }}</p>
  <p>{{ person.name }}{{ person.age }}</p>
  <button @click="updateage">更新年龄</button>

  <div>总结：在开发时候： 传递单个数据使用ref,有多个数据使用reactive</div>

  <p>计算属性测试：{{ age }}</p>

  <Child :age="age" @setAge="person.age++"></Child>
</template>

<script>
import {
  reactive,
  // readonly, //只读
  ref,
  watch,
  computed,
  onMounted,
  onBeforeUnmount,
} from "vue";
import Child from "./Child.vue";
export default {
  name: "App",
  setup() {
    // 初始化流程触发，相当于beforecreate和created生命周期函数
    console.log("setup()触发", this);

    // 生命周期钩子可以有多个，不会被覆盖，顺序触发
    onMounted(() => {
      console.log("onMount触发了1");
    });
    onMounted(() => {
      console.log("onMount触发了2");
    });
    onBeforeUnmount(() => {
      console.log("onBeforeUnmount卸载了");
    });

    const num = ref(0);
    // methods
    const update = () => {
      // 注意要变量.value
      num.value += 2;
    };

    const person = reactive({
      name: "haijing",
      age: 38,
    });
    const updateage = () => {
      person.age++;
    };
    // 监视属性
    watch(
      num,
      (newVal, oldVal) => {
        console.log("监视到数据变化", newVal, oldVal);
      },
      { deep: true, immediate: true }
    );
    // 计算属性
    // 写法一：只读
    const age = computed(() => {
      return person.age + "岁";
    });
    // 写法二：可读写
    // computed({
    //   get() {},
    //   set() {},
    // });

    // 记得暴露出去外面使用
    return { num, update, person, updateage, age };
  },
  components: {
    Child,
  },
};
</script>

<style>
</style>